import os.path
import time
import tkinter
from datetime import datetime
import tkinter as tk
from tkinter import *
from tkinter import ttk
from gupiao.views import views
from gupiao.rli import Calendar
from gupiao.celue import celue
from gupiao.huoquzhangtingban import HuoQuZhangTingBan
from gupiao.ZhuYingYeWu import ZhuYingYeWu
from gupiao.huoqusuoyoupiaohuositian import HuoQuSuoYouPiaoHuoSiTian
from gupiao.ZhangTingHuoSiTian import ZhangTingHuoSiTian
from gupiao.getallfiles import get_all_files
from gupiao.zijinliu_dapan import DaPanZiJinLiuLu
from tkinter import font


window = Tk()
window.title("复盘工具")
window.geometry("520x300")
width, height = window.winfo_reqwidth() + 200, 200


tab_control = ttk.Notebook(window)
tab_control.pack(expand=True, fill=BOTH)
tab1 = Frame(tab_control)
tab2 = Frame(tab_control)
tab3 = Frame(tab_control)
tab4 = Frame(tab_control)
tab5 = Frame(tab_control)
tab6 = Frame(tab_control)

tab_control.add(tab1, text="策略计算器")
tab_control.add(tab2, text="显示涨停板")
tab_control.add(tab3, text="策略研读")
tab_control.add(tab4, text="主营业务")
tab_control.add(tab5, text="涨停后四天涨跌幅")
tab_control.add(tab6, text="大盘资金流入情况")


buy_entry,input_entry1,input_entry2,input_entry3,result1,result2,result3,result4,dropdown=views(tab1)

def get_input():
    # total_input=  total_entry.get()
    total_input = 10000
    buy_input = buy_entry.get()
    user_input1 = input_entry1.get()
    user_input2 = input_entry2.get()
    user_input3 = input_entry3.get()
    if total_input == '':
        total_input = 0
    if user_input1 == '':
        user_input1 = 0
    if user_input2 == '':
        user_input2 = 0
    if user_input3 == '':
        user_input3 = 0
    if buy_input == '':
        buy_input = 0
    total_input = int(total_input)
    buy_input = float(buy_input)
    user_input1 = float(user_input1)
    user_input2 = float(user_input2)
    user_input3 = float(user_input3)
    dropdown_valuser = dropdown.get()

    sum = total_input
    print(total_input)
    buy_total = total_input * buy_input
    # 佣金
    yongjin=5+buy_total*0.00001
    if dropdown_valuser == '1/2':
        # 第一次卖出
        one_shell = sum * (1 / 2) * user_input1
        sum = sum - sum * (1 / 2)
        print(one_shell, sum)
    elif dropdown_valuser == '1/3':
        # 第一次卖出
        one_shell = sum * (1 / 3) * user_input1
        sum = sum - sum * (1 / 3)
        print(one_shell, sum)
    # 卖出税费
    shuifei_one=5+one_shell*(0.00001+0.0005)
    # 第二次卖出
    # rate2 = (user_input2 - user_input1) / user_input1
    # sum = sum * (1 + rate2)
    if user_input2 == 0:
        if dropdown_valuser == '1/2':
            two_shell = one_shell
        elif dropdown_valuser == '1/3':
            two_shell = one_shell * 2
        three_shell = 0
        print(two_shell, sum)
        shuifei_three = 0
    else:
        two_shell = sum * (1 / 2) * user_input2
        sum = sum - sum * (1 / 2)
        print(two_shell, sum)
        # 第三次卖出
        if user_input3 == 0:
            three_shell = two_shell
        else:
            # rate3 = (user_input3 - user_input2) / user_input2
            three_shell = sum * user_input3
        print(three_shell, sum)
        shuifei_three = 5 + three_shell * (0.00001 + 0.0005)
    # 卖出税费
    shuifei_two=5+two_shell*(0.00001+0.0005)
    total = one_shell + two_shell + three_shell-(shuifei_one+shuifei_two+shuifei_three+yongjin)
    total_rate = (total - buy_total) / buy_total * 100
    compare_money = total - buy_total
    compare_money = "{:.2f}".format(compare_money)
    total = "{:.2f}".format(total)
    buy_total = "{:.2f}".format(buy_total)
    total_rate = "{:.2f}".format(total_rate)

    result_text1 = f"{total}"
    result1.delete(0, tk.END)
    result1.insert(tk.END, result_text1)

    result_text2 = f"{buy_total}"
    result2.delete(0, tk.END)
    result2.insert(tk.END, result_text2)

    result_text3 = f"{compare_money}"
    result3.delete(0, tk.END)
    result3.insert(tk.END, result_text3)

    result_text4 = f"{total_rate}%"
    result4.delete(0, tk.END)
    result4.insert(tk.END, result_text4)


def clear_input():
    buy_entry.delete(0, tk.END)
    input_entry1.delete(0, tk.END)
    input_entry2.delete(0, tk.END)
    input_entry3.delete(0, tk.END)
    result1.delete(0, tk.END)
    result2.delete(0, tk.END)
    result3.delete(0, tk.END)
    result4.delete(0, tk.END)

def getdate():
    x, y = window.winfo_x()+8, window.winfo_y()+309
    print(window.winfo_x() )
    print(window.winfo_y() )
    print(x,y)
    for date in [Calendar((x, y), 'ur').selection()]:
        if date:
            date_str.set(date)
            print(date)

def getdate2():
    x, y = window.winfo_x()+8, window.winfo_y()+309
    print(window.winfo_x() )
    print(window.winfo_y() )
    print(x,y)
    for date in [Calendar((x, y), 'ur').selection()]:
        if date:
            date_str2.set(date)
            print(date)

def findscore():
    date_input = date_entry.get()
    print(date_input)
    a=date_input.split('-')
    year=a[0]
    ti=''.join(a)
    print(year,ti)
    lb.delete("1.0", "end")
    file=f"C:/Users/Administrator/Desktop/fupan/zhangtingbanshouban/{year}/{ti}.txt"
    if os.path.exists(file):
        with open(file,mode="r") as f:
            scores=f.readlines()
            for score in scores:
                score=score.split(',')
                score=' '.join(score)
                lb.insert(tk.END, score)

def createdata():
    now =datetime.now()
    year=now.year
    ti = time.strftime("%Y%m%d", time.localtime())
    # 涨停板
    result=HuoQuZhangTingBan(ti,year)
    print(result)
    print(type(result))
    if result == 1:
        tk.Label(tab2, text=f"{ti}\n生成数据成功!!!").place(x=30, y=100)
    elif result == 0:
        tk.Label(tab2, text=f"{ti}\n生成数据失败？？？").place(x=30, y=100)

def zhuyingyewu():
    lb_zyyw.delete("1.0", "end")
    code_input = code_entry.get()
    print(code_input)
    stock_zyjs_ths_dict=ZhuYingYeWu(code_input)
    zyyw=stock_zyjs_ths_dict["主营业务"][0]
    cplx=stock_zyjs_ths_dict["产品类型"][0]
    cpmc=stock_zyjs_ths_dict["产品名称"][0]
    jyfw=stock_zyjs_ths_dict["经营范围"][0]
    text=f'''\n
    主营业务：{zyyw}
    产品类型：{cplx}
    产品名称：{cpmc}
    经营范围：{jyfw}
    '''
    lb_zyyw.insert(tk.END, text)

def FindAll():
    lb_ztbhst.delete("1.0", "end")
    print('aaa')
    date_input2 = date_entry2.get()
    print(date_input2)
    date_input2=str(date_input2).split("-")
    date_input2=''.join(date_input2)
    all_stocks=HuoQuSuoYouPiaoHuoSiTian(date_input2)
    all_stocks_count=len(all_stocks)
    two['maximum'] = all_stocks_count
    two['value'] = 0
    all_stocks_infos=[]
    for i in range(all_stocks_count):
        two['value']=i+1
        tab5.update()
        time.sleep(0.05)
        tk.Label(tab5, text=f"{i+1}/{all_stocks_count}").place(x=450, y=10)
        code=all_stocks[i][0]
        code_name=all_stocks[i][1]
        day_zt=ZhangTingHuoSiTian(code,date_input2)
        day_1=day_zt['day_1']
        day_2=day_zt['day_2']
        day_3=day_zt['day_3']
        day_4=day_zt['day_4']
        all_stocks_infos.append([code,code_name,day_1,day_2,day_3,day_4])
    for info in all_stocks_infos:
        text=f"{info[0]},{info[1]},{info[2]},{info[3]},{info[4]},{info[5]}\n"
        file=f"C:/Users/Administrator/Desktop/fupan/zhangtingbanshouban/housitianshuju/{date_input2}.txt"
        with open(file,mode='a+',encoding="utf-8") as f:
            f.write(text)
        lb_ztbhst.insert(tk.END, text)


def History(event):
    date_entry2.delete(0, tk.END)
    print(111)
    ti=option_menu.get()
    print(ti)
    if ti=="历史记录":
        pass
    else:
        lb_ztbhst.delete("1.0", "end")
        file=f"C:/Users/Administrator/Desktop/fupan/zhangtingbanshouban/housitianshuju/{ti}.txt"
        with open(file,mode='r',encoding='utf-8',errors='ignore') as f:
            text=f.read()
            lb_ztbhst.insert(tk.END, text)
        f.close()


def DaPan():
    lb_dpzjlr.delete("1.0", "end")
    t=option_menu_dapan.get()
    if t == "查询天数":
        text="切换成天数"
        lb_dpzjlr.insert(tk.END, text)
    else:
        t=int(t)
        shuju=DaPanZiJinLiuLu(t)
        header="日期 上证-收盘价 上证-涨跌幅 主力净流入-净额 主力净流入-净占比 超大单净流入-净额 超大单净流入-净占比 大单净流入-净额 大单净流入-净占比 中单净流入-净额 中单净流入-净占比 小单净流入-净额 小单净流入-净占比   总计\n"
        lb_dpzjlr.insert(tk.END, header)
        for i in shuju:
            date=i["日期"]
            szsp=i["上证-收盘价"]
            zhangfu=i["上证-涨跌幅"]
            zljlr_net=i["主力净流入-净额"]
            zljlr_bili=i["主力净流入-净占比"]
            cdjlr_net=i["超大单净流入-净额"]
            cdjlr_bili=i["超大单净流入-净占比"]
            dzjlr_net=i["大单净流入-净额"]
            dzjlr_bili=i["大单净流入-净占比"]
            zxjlr_net=i["中单净流入-净额"]
            zxjlr_bili=i["中单净流入-净占比"]
            xdjlr_net=i["小单净流入-净额"]
            xdjlr_bili=i["小单净流入-净占比"]
            total=i["total"]
            lb_dpzjlr.insert(tk.END, f"{date} {szsp} {zhangfu} {zljlr_net} {zljlr_bili} {cdjlr_net} {cdjlr_bili} {dzjlr_net} {dzjlr_bili} {zxjlr_net} {zxjlr_bili} {xdjlr_net} {xdjlr_bili}   {total}\n")


option_var = tk.StringVar(tab5)
option_var.set("历史记录")  # 设置默认值
foldpath = "C:/Users/Administrator/Desktop/fupan/zhangtingbanshouban/housitianshuju/"
allfiles = get_all_files(foldpath)
options = ["历史记录"]+allfiles
# option_menu = tk.OptionMenu(tab5, option_var, *options,command=History)
# option_menu.config(width=10)
# option_menu.place(x=230,y=0,width=100)
# vscrollbar = ttk.Scrollbar(tab5, orient=VERTICAL)
# vscrollbar.config()
# option_menu.config()
# vscrollbar.place(x=230, y=0, height=200)
# option_menu.bind("<<MenuSelect>>", History)
option_menu = ttk.Combobox(tab5,textvariable=option_var,values=options)
option_menu.place(x=230,y=0,width=100)
option_menu.bind("<<ComboboxSelected>>",History)


font2 = font.Font(family='Courier', size=10)
lb = tk.Text(tab2, width=30,height=16,font=font2)

lb.place(x=250,y=0)

button1 = tk.Button(tab1, text="计算", command=get_input)
button1.place(x=155,y=210)

button2 = tk.Button(tab1, text="清除", command=clear_input)
button2.place(x=195,y=210)

date_str = tk.StringVar()
date_entry = ttk.Entry(tab2, textvariable=date_str)
date_entry.grid(row=0, column=1)
button3 = tk.Button(tab2, text="查找", command=findscore)
button3.place(x=200,y=0)
button4 = tk.Button(tab2, text="生成当天数据", command=createdata)
button4.place(x=30,y=50)

tk.Button(tab2, text='日期:', command=getdate).grid(row=0, column=0)

text=celue()
font3 = font.Font(family='Courier', size=10)
lb2 = tk.Text(tab3, width=60,height=16,font=font3)
lb2.place(x=0,y=0)
lb2.insert(tk.END, text)

tk.Label(tab4, text="股票代码：").place(x=30, y=10)
code_entry = tk.Entry(tab4)
code_entry.place(x=90, y=10)
button_code=tk.Button(tab4, text='查找:', command=zhuyingyewu)
button_code.place(x=250, y=10)
lb_zyyw = tk.Text(tab4, width=60,height=14,font=font2)
lb_zyyw.place(x=0,y=40)


tk.Button(tab5, text='日期:', command=getdate2).grid(row=0, column=0)
date_str2 = tk.StringVar()
date_entry2 = ttk.Entry(tab5, textvariable=date_str2)
date_entry2.grid(row=0, column=1)
button_code=tk.Button(tab5, text='查找', command=FindAll)
button_code.place(x=190, y=0)
# code_history=tk.Button(tab5, text='历史记录', command=History)
# code_history.place(x=240, y=0)

lb_ztbhst = tk.Text(tab5, width=60,height=14,font=font2)
lb_ztbhst.place(x=0,y=40)

two = ttk.Progressbar(tab5, orient=tkinter.HORIZONTAL, length=100, mode='determinate')
two.place(x=350,y=5)

button_code_dapan=tk.Button(tab6, text='查询', command=DaPan)
button_code_dapan.place(x=120, y=0)
option_var_dapan = tk.StringVar(tab6)
option_var_dapan.set("查询天数")  # 设置默认值
allfiles = [10,30,60,120]
options_dapan = ["查询天数"]+allfiles
# option_menu = tk.OptionMenu(tab5, option_var, *options,command=History)
# option_menu.config(width=10)
# option_menu.place(x=230,y=0,width=100)
# vscrollbar = ttk.Scrollbar(tab5, orient=VERTICAL)
# vscrollbar.config()
# option_menu.config()
# vscrollbar.place(x=230, y=0, height=200)
# option_menu.bind("<<MenuSelect>>", History)
option_menu_dapan = ttk.Combobox(tab6,textvariable=option_var_dapan,values=options_dapan)
option_menu_dapan.place(x=10,y=0,width=100)
option_menu_dapan.bind("<<ComboboxSelected>>")
lb_dpzjlr = tk.Text(tab6, width=200,height=14,font=font2)
lb_dpzjlr.place(x=0,y=40)





window.mainloop()
